<?php


namespace App\Http\Controllers\System;


use App\Http\Controllers\Controller;
use App\Http\Services\System\RoleService;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function list(Request $request, RoleService $roleService)
    {
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $res = $roleService->search($request->all());
        return success("Ok", $res);
    }

    //角色搜索
    public function search(Request $request, RoleService $roleService)
    {
        $param = $request->all();
        $param['limit'] = 20;
        $res = $roleService->search($param);
        $roles = array_column($res['data'], 'label', 'type');
        return result($roles, "角色搜索");
    }

    //修改、新建角色
    public function save(Request $request, RoleService $roleService)
    {
        $this->validate($request, [
            'label' => 'required',
            'type' => 'required'
        ]);
        $param = $request->all();
        $id = $param['id'] ?? "";
        if(!empty($id)){
            unset($param['id']);
            $res = $roleService->updateData($id, $param);
        }else{
            $res = $roleService->addData($param);
        }
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //获取角色的权限
    public function permission(Request $request, RoleService $roleService)
    {
        $this->validate($request, [
            'role_id' => 'required'
        ]);
        $param = $request->all();
        $res = $roleService->getPermission($param['role_id']);
        return result($res, "获取角色权限");
    }

    //修改角色的权限
    public function permissionSave(Request $request, RoleService $roleService)
    {
        $this->validate($request, [
            'role_id' => 'required',
            'menu_ids' => 'required'
        ]);
        $param = $request->all();
        $res = $roleService->savePermission($param['role_id'], $param);
        return $res['code'] === 0 ? success("操作成功") : error("操作失败", $res);
    }
}
